# -*- coding: utf-8 -*-

###################
#   miniTH
#   This program serves for serial change of photos size, to put watermarks
#   and at the same time for making thumbnails.
#   It can be useful for quick processing of big amount of pictures in order to put
#   them in web galleries or on websites.
#   Copyright (C) 2011 DooBLER
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
###################

###################
# svn: $Id: miniTH.py 20 2011-08-15 17:40:39Z MrDooBLER@gmail.com $
# Author: DooBLER http://doobler.net
###################

import sys
import os
import urllib
import re
import datetime

from PySide import QtCore
from PySide import QtGui
#from mainwindow import Ui_MainWindow
from uimainwindow import MyUi_MainWindow

from minith.graphics.MyMarchingAntsRectItem import MyMarchingAntsRectItem
from minith.models.myFileListModel import myFileListModel

from minith.widgets.MyHistogramWidget import MyHistogramWidget
from minith.widgets.My9BtnWidget import My9BtnWidget



VERSION = [0,1,0]
REVISION = "$Rev: 20 $"



class MiniTHForm(QtGui.QMainWindow):
    def __init__(self, settings, parent=None):
        QtGui.QMainWindow.__init__(self, parent)

        self.settings = settings
        
        self.ui = MyUi_MainWindow()
        
        self.ui.setupUi(self)

        #testowe okno dokowane
        #self.ui.dockWidget_2.close()


        self.histogram = My9BtnWidget(self.ui.dockWidgetContents_2)
        self.ui.verticalLayout_18.addWidget(self.histogram)

        self.histogram.valueChanged.connect(self.testOut)



        # zaznaczenie kadrowanie
        self.selection = MyMarchingAntsRectItem(0, 0, 70, 70)
        self.selection.sigMoved.connect(self.kadrPosChanged)
        self.selection.sigSizeChanged.connect(self.kadrSizeChanged)
        self.selection.sigDelSelection.connect(self.ui.kadrowanieBox.setChecked)

        self.sel_x = 0
        self.sel_y = 0
        self.sel_w = 70
        self.sel_h = 70
        self.sel_proportions = 0

        self.ramka = 0
        # zmienna przechowująca aktualny obrazek
        self.obrazek = None
        # znak wodny
        self.watermark = None

        # ścieżka do aktualnie wybranego katalogu
        self.file_path = os.path.expanduser('~')

        # dane dla obrazka i miniaturki
        self.obr_w = 0
        self.obr_h = 0
        self.obr_scale = 1
        self.obr_fit = 1
        self.obr_alignment = 1
        self.min_w = 0
        self.min_h = 0
        self.min_scale = 1
        self.min_fit = 1
        self.min_alignment = 1

        # dane dla znaku wodnego
        self.wm_w = 0
        self.wm_h = 0
        self.wm_align = 1

        # wczytanie ustawień i nadpisanie powyższych zmiennych
        self.readSettings()

        #ustawienie ikony głównego okna
        self.setWindowIcon(QtGui.QIcon("gfx/images16.png"))

        # model drzewa katalogów
        self.dir_model = QtGui.QFileSystemModel()
        self.dir_model.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.AllDirs)
        self.dir_model.setRootPath(self.file_path)
        
        # model listy plików
        # self.file_model = QtGui.QFileSystemModel()
        # self.file_model.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Files)
        # self.file_model.setRootPath( '/' )
        self.file_model = myFileListModel(self) 
        self.file_model.setRootPath(self.file_path )
        self.ui.dirLabel.setText(self.file_path)
        self.fileExtChanged() # zmienia filtr listy plików
        
        
        # ustawienia drzewa katalogów
        self.ui.dirTreeView.setModel(self.dir_model)
        self.ui.dirTreeView.setCurrentIndex(self.dir_model.index(self.file_path))
        self.ui.dirTreeView.hideColumn(1)
        self.ui.dirTreeView.hideColumn(2)
        self.ui.dirTreeView.hideColumn(3)
        self.ui.dirTreeView.resizeColumnToContents(0)
    
        self.ui.dirTreeView.expanded.connect(self.dirTreeWidth)
        self.ui.dirTreeView.collapsed.connect(self.dirTreeWidth)
        self.ui.dirTreeView.clicked.connect(self.dirTreeViewClicked)
        
        
        # ustawienia listy plików
        self.ui.filesListView.setModel(self.file_model)
        self.ui.filesListView.clicked.connect(self.filesListViewClicked)
        
        
        # checkBoxy z rozszerzeniami plików
        self.ui.jpgCheckBox.stateChanged.connect(self.fileExtChanged)
        self.ui.pngCheckBox.stateChanged.connect(self.fileExtChanged)
        self.ui.gifCheckBox.stateChanged.connect(self.fileExtChanged)
        self.ui.bmpCheckBox.stateChanged.connect(self.fileExtChanged)

        # MENU ---------
        self.ui.actionSelectLanguage.triggered.connect(self.actionSelectLanguageTriggered)
        self.ui.actionCheckForUpdates.triggered.connect(self.actionCheckForUpdatesTriggered)
        self.ui.actionExit.triggered.connect(self.actionExitTriggered)
        self.ui.actionAbout.triggered.connect(self.actionAboutTriggered)

        # okna dokowane w menu
        self.ui.menuDokowane.addAction(self.ui.dirDockWidget.toggleViewAction())
        self.ui.menuDokowane.addAction(self.ui.filesDockWidget.toggleViewAction())
        self.ui.menuDokowane.addAction(self.ui.navDockWidget.toggleViewAction())
        self.ui.menuDokowane.addAction(self.ui.watermarkDockWidget.toggleViewAction())



        # kontrolki do zooma
        self.ui.zoomSpinBox.valueChanged.connect(self.zoomSpinBoxChanged)
        self.ui.zoomSlider.valueChanged.connect(self.zoomSliderChanged)
        self.ui.zoom11Btn.clicked.connect(self.zoom11BtnClicked)
        self.ui.zoomFitBtn.clicked.connect(self.zoomFitBtnClicked)
        #self.ui.zoomFitBtn.setText('')
        #self.ui.zoomFitBtn.setIcon(QtGui.QIcon("gfx/resize_picture.png"))

        
        # dock nawigacja
        self.ui.prevBtn.clicked.connect(self.prevBtnClicked)
        self.ui.nextBtn.clicked.connect(self.nextBtnClicked)
        self.ui.prevxBtn.clicked.connect(self.prevXBtnClicked)
        self.ui.nextxBtn.clicked.connect(self.nextXBtnClicked)
        self.ui.goAllBtn.clicked.connect(self.goAllBtnClicked)


        # dock znak wodny
        self.ui.watermarkOpenBtn.clicked.connect(self.watermarkOpenBtnClicked)
        self.ui.wmWSpinBox.valueChanged.connect(self.setWatermark)
        self.ui.wmHSpinBox.valueChanged.connect(self.setWatermark)
        self.ui.wmButtons.valueChanged.connect(self.setWatermark)


        # zakladka obrazek
        self.ui.obrWSpinBox.valueChanged.connect(self.setImageSize)
        self.ui.obrHSpinBox.valueChanged.connect(self.setImageSize)
        self.ui.obrSizeLink.toggled.connect(self.obrSizeLinkToggled)
        self.ui.obrDopRadio_1.toggled.connect(self.setImageParams)
        self.ui.obrDopRadio_2.toggled.connect(self.setImageParams)
        self.ui.obrDopRadio_3.toggled.connect(self.setImageParams)
        self.ui.obrDopRadio_4.toggled.connect(self.setImageParams)
        self.ui.obrUklButtons.valueChanged.connect(self.setImageParams)


        # zakladka Miniaturka
        self.ui.minWSpinBox.valueChanged.connect(self.setThumbnailSize)
        self.ui.minHSpinBox.valueChanged.connect(self.setThumbnailSize)
        self.ui.minSizeLink.toggled.connect(self.minSizeLinkToggled)
        self.ui.minDopRadio_1.toggled.connect(self.setThumbnailParams)
        self.ui.minDopRadio_2.toggled.connect(self.setThumbnailParams)
        self.ui.minDopRadio_3.toggled.connect(self.setThumbnailParams)
        self.ui.minDopRadio_4.toggled.connect(self.setThumbnailParams)
        self.ui.minUklButtons.valueChanged.connect(self.setThumbnailParams)


        # zakladka kadrowanie
        self.ui.kadrowanieBox.toggled.connect(self.kadrowanieBoxChanged)
        self.ui.p1spin.valueChanged.connect(self.kadrPosSpinChanged)
        self.ui.p2spin.valueChanged.connect(self.kadrPosSpinChanged)
        self.ui.p3spin.valueChanged.connect(self.kadrWSpinChanged)
        self.ui.p4spin.valueChanged.connect(self.kadrHSpinChanged)
        self.ui.kadrSizeLink.toggled.connect(self.kadrSizeLinkToggled)

        
        # graphicViews
        self.imageOnScene = None
        self.scene = QtGui.QGraphicsScene();
        #self.ui.graphicsView.setDragMode(QtGui.QGraphicsView.RubberBandDrag)
        #self.ui.graphicsView.setRubberBandSelectionMode(QtCore.Qt.IntersectsItemBoundingRect)
        self.ui.graphicsView.setScene(self.scene)
        #pedzel = QtGui.QBrush()
        #pedzel.setStyle(QtCore.Qt.Dense7Pattern)
        #self.ui.graphicsView.setForegroundBrush(pedzel)
        
        
        
        # http://www.qtcentre.org/threads/11470-drawForeground-update-trouble
        # http://www.qtcentre.org/archive/index.php/t-6279.html


        # test
        self.ui.testBtn.clicked.connect(self.testBtnClick)

        # sprawdzenie czy jest nowa wersja
        self.actionCheckForUpdatesTriggered(showfail=False)


    def kadrSizeLinkToggled(self, checked):
        if checked:
            p3spin = self.ui.p3spin.value()
            p4spin = self.ui.p4spin.value()
            if p3spin == 0 or p4spin == 0:
                self.sel_proportions = 1
                self.selection.setProportions(1)
            else:
                self.sel_proportions = float(p3spin) / float(p4spin)
                self.selection.setProportions(self.sel_proportions)

            self.ui.kadrSizeLink.setToolTip(str(self.sel_proportions))
        else:
            self.ui.kadrSizeLink.setToolTip('')
            self.selection.setProportions(0)


    def kadrPosSpinChanged(self):
        rect = self.imageOnScene.boundingRect()
        x = self.ui.p1spin.value()
        y = self.ui.p2spin.value()

        if x != self.sel_x:
            self.sel_x = x
        elif y != self.sel_y:
            self.sel_y = y

        self.ui.p3spin.setMaximum(rect.width()-x-1)
        self.ui.p4spin.setMaximum(rect.height()-y-1)

        self.selection.setPos(QtCore.QPointF(x, y))


    def kadrWSpinChanged(self):
        size = self.selection.setWidth(self.ui.p3spin.value())

        max = self.selection.getMax()
        self.ui.p1spin.setMaximum(max.x())
        self.ui.p4spin.setMaximum(max.height())
        
        self.ui.p4spin.setValue(size.y())

    def kadrHSpinChanged(self):
        size = self.selection.setHeight(self.ui.p4spin.value())

        max = self.selection.getMax()
        self.ui.p2spin.setMaximum(max.y())
        self.ui.p3spin.setMaximum(max.width())

        self.ui.p3spin.setValue(size.x())


    def kadrPosChanged(self, value):
        self.ui.p1spin.setValue(value.x())
        self.ui.p2spin.setValue(value.y())

    def kadrSizeChanged(self, value):
        self.ui.p3spin.setValue(value.x())
        self.ui.p4spin.setValue(value.y())


    def kadrSetMax(self):
        max = self.selection.getMax()

        self.ui.p1spin.setMaximum(max.x())
        self.ui.p2spin.setMaximum(max.y())
        self.ui.p3spin.setMaximum(max.width())
        self.ui.p4spin.setMaximum(max.height())


    def closeEvent(self, event):
        self.writeSettings()
        event.accept()

    def writeSettings(self):
        self.settings.beginGroup("MainWindow")
        if self.isMaximized():
            self.settings.setValue("maximized", self.isMaximized())
        else:
            self.settings.setValue("size", self.size())
            self.settings.setValue("pos", self.pos())
            self.settings.setValue("maximized", 'false')

        self.settings.setValue("file_path", self.file_path)

        self.settings.setValue("obr_w", self.obr_w)
        self.settings.setValue("obr_h", self.obr_h)
        self.settings.setValue("obr_quality", self.ui.obrQualitySpinBox.value())


        if self.ui.obrSizeLink.isChecked():
            self.settings.setValue("obr_size_link", True)
            self.settings.setValue("obr_scale", self.obr_scale)
        else:
            self.settings.setValue("obr_size_link", False)
            self.settings.setValue("obr_scale", 1)

        self.settings.setValue("min_w", self.min_w)
        self.settings.setValue("min_h", self.min_h)
        self.settings.setValue("min_quality", self.ui.minQualitySpinBox.value())

        if self.ui.minSizeLink.isChecked():
            self.settings.setValue("min_size_link", True)
            self.settings.setValue("min_scale", self.min_scale)
        else:
            self.settings.setValue("min_size_link", False)
            self.settings.setValue("min_scale", 1)

        self.settings.endGroup()

    def readSettings(self):
        self.settings.beginGroup("MainWindow")
        self.resize(self.settings.value("size", QtCore.QSize(800, 550)))
        self.move(self.settings.value("pos", QtCore.QPoint(50, 50)))
        if self.settings.value("maximized", 'false')  != "false":
            self.showMaximized()

        self.file_path = self.settings.value("file_path", self.file_path)

        self.obr_w = int(self.settings.value("obr_w", self.obr_w))
        self.obr_h = int(self.settings.value("obr_h", self.obr_h))
        self.ui.obrWSpinBox.setValue(self.obr_w)
        self.ui.obrHSpinBox.setValue(self.obr_h)
        self.ui.obrQualitySpinBox.setValue(int(self.settings.value("obr_quality", 75)))

        self.ui.obrSizeLink.setChecked(self.settings.value("obr_size_link", 'false') != 'false')
        self.obr_scale = float(self.settings.value("obr_scale", self.obr_scale))
        self.ui.obrSizeLink.setToolTip(str(self.obr_scale))

        self.min_w = int(self.settings.value("min_w", self.min_w))
        self.min_h = int(self.settings.value("min_h", self.min_h))
        self.ui.minWSpinBox.setValue(self.min_w)
        self.ui.minHSpinBox.setValue(self.min_h)
        self.ui.minQualitySpinBox.setValue(int(self.settings.value("min_quality", 75)))

        self.ui.minSizeLink.setChecked(self.settings.value("min_size_link", 'false') != 'false')
        self.min_scale = float(self.settings.value("min_scale", self.min_scale))
        self.ui.minSizeLink.setToolTip(str(self.min_scale))

        self.settings.endGroup()

        if self.min_w > 0 and self.min_h > 0:
            self.ui.minDopGroupBox.setEnabled(True)



    def saveImage(self, srcimg):

        opath = os.path.join(self.file_path, 'out')
        mpath = os.path.join(self.file_path, 'out', 'm')
        index = self.ui.filesListView.currentIndex()
        index = index.row()+1
        ofile = '%d.jpg' % (index)
        mfile = '%d_mini.jpg' % (index)

        # sprawdzenie czy istnieje katalog out
        if not os.path.exists(opath):
            os.mkdir(opath)

        # jeśli obrazek ma być kadrowany
        if self.ui.kadrowanieBox.isChecked():
            rect = self.selection.rect()
            pos = self.selection.pos()
            kadrX = pos.x()
            kadrY = pos.y()
            kadrW = rect.width()+1
            kadrH = rect.height()+1

            srcimg2 = srcimg.copy(kadrX, kadrY, kadrW, kadrH)
        else:
            srcimg2 = srcimg

        # zmniejszenie obrazka
        oobr = self.scaleImage(srcimg2, self.obr_w, self.obr_h, self.obr_fit, self.obr_alignment)
        # dodanie znaku wodnego jeśli ma być
        if  self.watermark:
            wmx = 0
            wmy = 0
            wmw = self.watermark.width()
            wmh = self.watermark.height()
            destw = oobr.width()
            desth = oobr.height()

            if self.wm_align in [1,2,3]:
                wmy = 0+self.wm_h
            elif self.wm_align in [4,5,6]:
                wmy = round((desth/2.0)-(wmh/2.0))
            else:
                wmy = desth-wmh-self.wm_h

            if self.wm_align in [1,4,7]:
                wmx = 0+self.wm_w
            elif self.wm_align in [2,5,8]:
                wmx = round((destw/2.0)-(wmw/2.0))
            else:
                wmx = destw-wmw-self.wm_w

            painter = QtGui.QPainter(oobr)
            painter.drawImage(wmx, wmy, self.watermark)
            painter.save()
            painter.restore()
            painter.end()
        # zapisanie obrazka w katalogu out
        oobr.save(os.path.join(opath, ofile), 'JPG', self.ui.obrQualitySpinBox.value())
        
        # sprawdzenie czy ma być miniaturka - w, h >  0
        if self.min_w > 0 and self.min_h > 0:

            # sprawdzenie czy istnieje katalog out/m
            if not os.path.exists(mpath):
                os.mkdir(mpath)

            # zmniejszenie obrazka
            mobr = self.scaleImage(srcimg2, self.min_w, self.min_h, self.min_fit, self.min_alignment)

            # zapisanie w kataligu out/m
            mobr.save(os.path.join(mpath, mfile), 'JPG', self.ui.minQualitySpinBox.value())


    def scaleImage(self, srcimg, w, h, fit, alignment):
        if srcimg:
            src_width = srcimg.width()
            src_height = srcimg.height()

            aobr = None

            if w > 0 and h > 0:
                if fit == 2:
                    dest_k = float(w)/float(h)
                    src_k = float(src_width)/float(src_height)

                    if src_k < dest_k:
                        # zrodlo jest wyzsze
                        copy_w = src_width;
                        copy_h = round(src_width/dest_k);

                        copy_x = 0;
                        if alignment <= 3:
                            copy_y = 0
                        elif alignment >= 7:
                            copy_y = round(src_height-copy_h)
                        else:
                            copy_y = round((src_height-copy_h)/2.0)

                        aobr = srcimg.copy(copy_x, copy_y, copy_w, copy_h)
                    elif src_k > dest_k: 
                        # zrodlo jest szersze
                        copy_w = round(src_height*dest_k);
                        copy_h = src_height;

                        if alignment in [1,4,7]:
                            copy_x = 0
                        elif alignment in [3,6,9]:
                            copy_x = round(src_width-copy_w);
                        else:
                            copy_x = round((src_width-copy_w)/2.0);
                        copy_y = 0;
                        aobr = srcimg.copy(copy_x, copy_y, copy_w, copy_h)
                    else:
#                        copy_w = src_width;
#                        copy_h = src_height;
#                        copy_x = 0;
#                        copy_y = 0;
                        aobr = srcimg

                    aobr = aobr.scaled(w, h, QtCore.Qt.IgnoreAspectRatio, QtCore.Qt.SmoothTransformation)
                elif fit == 3:
                    aobr = srcimg.scaledToWidth(w, QtCore.Qt.SmoothTransformation)
                elif fit == 4:
                    aobr = srcimg.scaledToHeight(h, QtCore.Qt.SmoothTransformation)
                else:
                    aobr = srcimg.scaled(w, h, QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)

        return aobr
                

    def setImageSize(self):
        new_w = self.ui.obrWSpinBox.value()
        new_h = self.ui.obrHSpinBox.value()

        if new_w != self.obr_w or new_h != self.obr_h:
            if self.ui.obrSizeLink.isChecked():
                if new_w != self.obr_w:
                    self.obr_w = new_w
                    self.obr_h = round(float(new_w) / self.obr_scale)
                    self.ui.obrHSpinBox.setValue(self.obr_h)
                else:
                    self.obr_h = new_h
                    self.obr_w = round(new_h * self.obr_scale)
                    self.ui.obrWSpinBox.setValue(self.obr_w)
            else:
                self.obr_w = new_w
                self.obr_h = new_h


    def obrSizeLinkToggled(self, checked):
        if checked:
            if self.obr_w == 0 or self.obr_h == 0:
                self.obr_scale = 1
            else:
                self.obr_scale = float(self.obr_w) / float(self.obr_h)

            self.ui.obrSizeLink.setToolTip(str(self.obr_scale))
        else:
            self.ui.obrSizeLink.setToolTip('')

    def setImageParams(self):
        if self.ui.obrDopRadio_1.isChecked():
            self.obr_fit = 1
        elif self.ui.obrDopRadio_2.isChecked():
            self.obr_fit = 2
        elif self.ui.obrDopRadio_3.isChecked():
            self.obr_fit = 3
        else:
            self.obr_fit = 4

        if self.obr_fit == 2:
            self.ui.obrUklGroupBox.setEnabled(True)
        else:
            self.ui.obrUklGroupBox.setEnabled(False)

        self.obr_alignment = self.ui.obrUklButtons.getValue()


    def setThumbnailSize(self):
        new_w = self.ui.minWSpinBox.value()
        new_h = self.ui.minHSpinBox.value()

        if new_w != self.min_w or new_h != self.min_h:
            if self.ui.minSizeLink.isChecked():
                if new_w != self.min_w:
                    self.min_w = new_w
                    self.min_h = round(float(new_w) / self.min_scale)
                    self.ui.minHSpinBox.setValue(self.min_h)
                else:
                    self.min_h = new_h
                    self.min_w = round(new_h * self.min_scale)
                    self.ui.minWSpinBox.setValue(self.min_w)
            else:
                self.min_w = new_w
                self.min_h = new_h

        if self.min_w > 0 and self.min_h > 0:
            if not self.ui.minDopGroupBox.isEnabled():
                self.ui.minDopGroupBox.setEnabled(True)
                if self.min_fit == 2:
                    self.ui.minUklGroupBox.setEnabled(True)
        else:
            if self.ui.minDopGroupBox.isEnabled():
                self.ui.minDopGroupBox.setEnabled(False)
                self.ui.minUklGroupBox.setEnabled(False)

    def minSizeLinkToggled(self, checked):
        if checked:
            if self.min_w == 0 or self.min_h == 0:
                self.min_scale = 1
            else:
                self.min_scale = float(self.min_w) / float(self.min_h)

            self.ui.minSizeLink.setToolTip(str(self.min_scale))
        else:
            self.ui.minSizeLink.setToolTip('')

    def setThumbnailParams(self):
        if self.ui.minDopRadio_1.isChecked():
            self.min_fit = 1
        elif self.ui.minDopRadio_2.isChecked():
            self.min_fit = 2
        elif self.ui.minDopRadio_3.isChecked():
            self.min_fit = 3
        else:
            self.min_fit = 4

        if self.min_fit == 2:
            self.ui.minUklGroupBox.setEnabled(True)
        else:
            self.ui.minUklGroupBox.setEnabled(False)

        self.min_alignment = self.ui.minUklButtons.getValue()
                

    def setWatermark(self):
        self.wm_w = self.ui.wmWSpinBox.value()
        self.wm_h = self.ui.wmHSpinBox.value()

        self.wm_align = self.ui.wmButtons.getValue()
    

    def kadrowanieBoxChanged(self, stan):
        """
        Pokazuje lub ukrywa kwadrat zaznaczenia
        """
        if stan:
            self.selection.setPos(QtCore.QPointF(0,0))
            self.selection.setRect(0,0,100,100)
            self.scene.addItem(self.selection)
            self.selection.setZValue(100)
        else:
            self.scene.removeItem(self.selection)

        
    # funkcje zooma
    def zoomSliderChanged(self, value):
        value = int(value)
        self.zoom(value)
        self.ui.zoomSpinBox.setValue(value)
        
    def zoomSpinBoxChanged(self, value):
        value = self.ui.zoomSpinBox.value()
        self.zoom(value)
        self.ui.zoomSlider.setValue(value)
        
    def zoom(self, zoom):
        zoom = zoom/100.0
        matrix = QtGui.QMatrix()
        matrix.scale(zoom,zoom)
        self.ui.graphicsView.setMatrix(matrix)
        self.selection.setZoom(zoom)
        
    def zoom11BtnClicked(self):
        self.ui.graphicsView.resetMatrix()
        self.ui.zoomSpinBox.setValue(100)
        self.ui.zoomSlider.setValue(100)
        
    def zoomFitBtnClicked(self):
        if self.imageOnScene:
            self.ui.graphicsView.fitInView(self.imageOnScene,QtCore.Qt.KeepAspectRatio)
            self.ui.graphicsView.centerOn(self.imageOnScene)
        
        matrix = self.ui.graphicsView.matrix()
        zoom = int(matrix.m11()*100.0)
        self.ui.zoomSpinBox.setValue(zoom)
        self.ui.zoomSlider.setValue(zoom)
        

    def watermarkOpenBtnClicked(self):
        self.watermark = QtGui.QImage()

        fileName = QtGui.QFileDialog.getOpenFileName(self, self.tr("Open Image"), self.file_path, "Image Files (*.png *.jpg *.bmp)")

        if fileName[0] != '':
            self.watermark.load(fileName[0])

            self.ui.wmImgLabel.setPixmap(QtGui.QPixmap.fromImage(self.watermark))

        
    def filesListViewClicked(self, item):
        """
        Funkcja zmienia obrazek w oknie podglądu
        na wybrany w liście plików
        """
        print self.file_model.filePath(item)
        
        if self.imageOnScene != None:
            self.scene.removeItem(self.imageOnScene)

        # wczytanie obrazka do QImge
        self.obrazek = QtGui.QImage()
        self.obrazek.load(self.file_model.filePath(item))
        # dodanie obrazka do sceny
        self.pixmap = QtGui.QPixmap.fromImage(self.obrazek)
        self.imageOnScene = self.scene.addPixmap(self.pixmap)

        #dopasowanie wielkości sceny do obrazka
        self.scene.setSceneRect(self.imageOnScene.boundingRect())

        # zmniejszejszenie obrazka do rozmiarów okna i wycentrowanie
        self.ui.graphicsView.fitInView(self.imageOnScene,QtCore.Qt.KeepAspectRatio)
        self.ui.graphicsView.centerOn(self.imageOnScene)

        # ustawienie kontrolek zoomu
        matrix = self.ui.graphicsView.matrix()
        zoom = int(matrix.m11()*100)
        self.ui.zoomSpinBox.setValue(zoom)
        self.ui.zoomSlider.setValue(zoom)

        
   
        
    def testBtnClick(self):
        """
        Obsługa guzika testowego
        """
        self.histogram.setValue(self.histogram.getValue()+1)


#        print self.selection.rect()
#        print os.path.join(self.file_path, 'm', 'test.jpg')
#        if not self.kwadrat:
##            pedzel = QtGui.QBrush()
##            pedzel.setStyle(QtCore.Qt.SolidPattern)
##            penn = QtGui.QPen(pedzel, 1)
##            self.kwadrat = QtGui.QGraphicsRectItem(10, 10, 70, 70)
#            self.kwadrat = MyMarchingAntsRectItem(0, 0, 70, 70)
##            self.kwadrat.setPen(penn)
#            self.scene.addItem(self.kwadrat)
#        else:
#            pedzel = QtGui.QBrush()
#            pedzel.setStyle(QtCore.Qt.SolidPattern)
#            penn = QtGui.QPen(pedzel, 3)
#            self.kwadrat.setPen(penn)
#

    def testOut(self, abcd):
        print 'to:', abcd
        
       
       
       
    # fukcje przycisków nawigacji
    def prevBtnClicked(self):
        """
        Zapisuje obraz i zaznacza poprzedni
        """
        if self.obr_w > 0 and self.obr_h > 0:
            self.saveImage(self.obrazek)
            self.changeListItem(False)
        else:
            QtGui.QMessageBox.warning(self, self.tr("Error"), self.tr("Height and width of the image must be greater than 0."), QtGui.QMessageBox.Ok)

    def nextBtnClicked(self):
        """
        Zapisuje obraz i zaznacza następny
        """
        if self.obr_w > 0 and self.obr_h > 0:
            self.saveImage(self.obrazek)
            self.changeListItem()
        else:
            QtGui.QMessageBox.warning(self, self.tr("Error"), self.tr("Height and width of the image must be greater than 0."), QtGui.QMessageBox.Ok)

    def prevXBtnClicked(self):
        """
        Zaznacza poprzedni obraz
        """
        self.changeListItem(False)

    def nextXBtnClicked(self):
        """
        Zaznacza następny obraz
        """
        self.changeListItem()

    def goAllBtnClicked(self):
        """
        Przerabia wszystkie obrazy z listy plików
        """
        if self.obr_w > 0 and self.obr_h > 0:
            self.ui.filesListView.setCurrentIndex(self.file_model.index(0, 0))
            self.filesListViewClicked(self.file_model.index(0, 0))
            self.ui.filesListView.setFocus()

            ileimg = self.file_model.rowCount(0)

            self.ui.progressBar.setMaximum(ileimg-1)
            self.ui.progressBar.setValue(0)

            for i in range(ileimg):
                self.saveImage(self.obrazek)
                self.changeListItem()

                self.ui.progressBar.setValue(i)
        else:
            QtGui.QMessageBox.warning(self, self.tr("Error"), self.tr("Height and width of the image must be greater than 0."), QtGui.QMessageBox.Ok)




    def changeListItem(self, nextItem = True):
        """
        Funkcja przesówa zaznaczenie w liście plików
        do góry lub w dół
        """
        obecny = self.ui.filesListView.currentIndex().row()
        
        if nextItem:
            zmieniony = obecny + 1
        else:
            zmieniony = obecny - 1

        if self.file_model.hasIndex(zmieniony,0):
            self.ui.filesListView.setCurrentIndex(self.file_model.index(zmieniony, 0))
            self.filesListViewClicked(self.file_model.index(zmieniony, 0))
            self.ui.filesListView.setFocus()
            return True
        else:
            return False
            
        
            
        
    def dirTreeWidth(self):
        """
        Dostosowuje szerokość dirTree
        """
        self.ui.dirTreeView.resizeColumnToContents(0)
        
        
    def dirTreeViewClicked(self, item):
        """
        Slot wybrania katalogu w liściek atalogów
        """
        self.file_path = self.dir_model.filePath(item)
        
        self.file_model.setRootPath(self.file_path)
    
        self.dir_model.filePath(item)
        
        self.dirTreeWidth()
        
        self.ui.dirLabel.setText(self.file_path)
        
        
    def fileExtChanged(self):
        """
            Sprawdza stan checkboksów z nazwami plików
            i zmienia filtr nazwy plików w modelu
        """
        namefilters = []
        
        if self.ui.jpgCheckBox.isChecked():
            namefilters.append('*.jpg')
            namefilters.append('*.jpeg')
        
        if self.ui.pngCheckBox.isChecked():
            namefilters.append('*.png')
            
        if self.ui.gifCheckBox.isChecked():
            namefilters.append('*.gif')
            
        if self.ui.bmpCheckBox.isChecked():
            namefilters.append('*.bmp')
        
        if len(namefilters) < 1:
            self.ui.jpgCheckBox.setChecked(True)
            namefilters.append('*.jpg')
            namefilters.append('*.jpeg')
        
        self.file_model.setNameFilters(namefilters)


    def actionSelectLanguageTriggered(self):

        tablangname = []
        tablangcode = []

        size = self.settings.beginReadArray("languages")
        for i in range(size):
            self.settings.setArrayIndex(i)

            langname = settings.value("n")
            langcode = settings.value("c")
            tablangname.append(langname)
            tablangcode.append(langcode)

        self.settings.endArray()

        item, ok = QtGui.QInputDialog.getItem(self, self.tr("Select language"), self.tr("Language:"), tablangname, 0, False)
        if ok and item != '':
            langcode = tablangcode[tablangname.index(item)]

            prevlang = self.settings.value("app/language", 'en_GB')
            if prevlang != langcode:
                self.settings.setValue("app/language", langcode)

                QtGui.QMessageBox.warning(self, self.tr("Language changed"), self.tr("You have to run program again for the changes to take effect."), QtGui.QMessageBox.Ok)

    def actionExitTriggered(self):
        self.close()

    def actionCheckForUpdatesTriggered(self, checked=False, showfail=True):
        """
        Funkcja sprawdza czy jest dostępna nowa wersja programu
        """
        today = datetime.date.today()
        lastupdate = self.settings.value("app/last_update", '2011-01-02')
        lastupdate = datetime.datetime.strptime(lastupdate, '%Y-%m-%d').date()
        check_interval = datetime.timedelta(days=7)

        if (lastupdate+check_interval) <= today or showfail:
            self.settings.setValue("app/last_update", str(today))

            page = urllib.urlopen('http://apps.doobler.net/minith/up').read()

            wver = re.compile('ver_(\d+\.\d+\.\d+)_ver')
            ver = re.findall(wver,page)
            if ver:
                ver = ver[0].split('.')

            update = False
            if int(ver[0]) > VERSION[0]:
                update = True
            elif int(ver[0]) == VERSION[0] and int(ver[1]) > VERSION[1]:
                update = True
            elif int(ver[0]) == VERSION[0] and int(ver[1]) == VERSION[1] and int(ver[2]) > VERSION[2]:
                update = True

            if update:
                pdatetext = self.tr("""Your version is: <b>%s</b><br />
                The new version is: <b>%s</b><br />
                Do you want to go to the download page?""") % (str(VERSION[0])+'.'+str(VERSION[1])+'.'+str(VERSION[2]), ver[0]+'.'+ver[1]+'.'+ver[2])

                ret = QtGui.QMessageBox.information(self, self.tr("New version is available"), pdatetext, QtGui.QMessageBox.No | QtGui.QMessageBox.Yes )
                if ret == QtGui.QMessageBox.StandardButton.Yes:
                    QtGui.QDesktopServices.openUrl('http://apps.doobler.net/minith')
            else:
                if showfail:
                    QtGui.QMessageBox.information(self, self.tr("New version is not available."), self.tr("New version is not available."), QtGui.QMessageBox.Ok )


    def actionAboutTriggered(self):
        # John Doe
        a = self.tr('Version:')
        aa = str(VERSION[0])+'.'+str(VERSION[1])+'.'+str(VERSION[2])
        b = self.tr('Revision:')
        bb = REVISION
        c = self.tr('Author:')
        cc = 'DooBLER'
        d = self.tr('Translation author:')
        dd = self.tr('John Doe', 'translation author')
        abouttext = a+' '+aa+'<br />'+b+' '+bb+'<br /><br />'+c+' '+cc+'<br />'+d+' '+dd+'<br /><br />Icons used in this app comes from http://www.fatcow.com/'
        aboutbox = QtGui.QMessageBox()
        aboutbox.setText("<b>miniTH</b>")
        aboutbox.setInformativeText(abouttext)
        aboutbox.setIconPixmap(QtGui.QPixmap("gfx/images32.png"))
        aboutbox.exec_()




if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)

    app.setOrganizationName("DooBLER")
    app.setOrganizationDomain("doobler.net")
    app.setApplicationName("miniTH")

    settings = QtCore.QSettings('config.ini', QtCore.QSettings.IniFormat)

    lang = settings.value("app/language", 'en_GB')
    if lang != 'en_GB':
        translator = QtCore.QTranslator()
        translator.load('language/'+lang)
        app.installTranslator(translator)

    form = MiniTHForm(settings)
    form.show()
    sys.exit(app.exec_())
